import BaseStorage from './base-storage';

class LocalSessionStorage extends BaseStorage {
    /**
     * localStorage和seesionStorage构造函数
     * @param {string} prefix 前缀，区分不同模块及场景
     * @param {string} type 值为：localStorage|sessionStorage
     */
    constructor(type, prefix) {
        super(type, prefix);
        this.storage = localStorage;
        if(type === 'sessionStorage') {
            this.storage = sessionStorage;
        }
    }

    /**
     * 将name作为变量名，payload作为值储存到sorage中
     * @param {string} name 要存储的storage名称
     * @param {string|object} payload 要设置storage的值
     */
    setItem(name, payload) {
        let value = payload;
        try {
            if (Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object String]') {
                value = JSON.stringify(value);
            }
            this.storage.setItem(`${this.prefix}${name}`, value);
        } catch (e) {
            this.removeItem();
        }
    }

    /**
     * 根据name获取storage中的值
     * @param {string} name
     * @param {object} payload 附加参数，暂时没有用
     * @returns
     */
    getItem(name, payload) {
        let val = this.storage.getItem(`${this.prefix}${name}`);
        try {
            return JSON.parse(val);
        } catch (e) {
            return val;
        }
    }

    /**
     * 根据名称移除storage，若不传则移除所有
     * @param {string=} name
     */
    removeItem(name) {
        if(name) {
            this.storage.removeItem(`${this.prefix}${name}`);
        } else {
            this.storage.clear();
        }

    }
}

export default LocalSessionStorage;
